from flask import Flask, render_template, request, redirect, url_for, session
import functools

app = Flask(__name__)

app.secret_key = "q1w2e3r4t5y6u7i8o9p0"


# 装饰器
def auth(func):
    @functools.wraps(func)  # 避免被装饰函数名都是inner而报错
    def inner(*args, **kwargs):
        # session判断
        userName = session.get("user")
        if not userName:
            return redirect(url_for("login"))

        return func(*args, **kwargs)

    return inner


DATA_DICT = {
    1: {"name": "王语嫣", "age": 22},
    2: {"name": "木婉清", "age": 21},
    3: {"name": "程灵素", "age": 18},
}


# 默认支持GET请求，可在methods中配置
@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html")

    # print(request.form)  # 拿到表单所有数据
    # print(request.form.get("user"))  # 拿到具体name的数据
    # return request.form  # 返回json格式的数据包
    user = request.form.get("user")
    pwd = request.form.get("pwd")
    if user == "王源" and pwd == "123456":
        session["user"] = "王源"
        return redirect("/index")
    error = "用户名/密码有误！"
    return render_template("login.html", error=error)


# endpoint表示别名，不能重名，默认等于函数名
@app.route("/index", endpoint="idx")
@auth
def index():
    data_dict = DATA_DICT
    return render_template("index.html", data_dict=data_dict)


@app.route("/edit", methods=["GET", "POST"])
@auth
def edit():
    # 获取get传过来的data【都是str类型】
    nid = request.args.get("nid")
    nid = int(nid)
    info = DATA_DICT[nid]

    if request.method == "POST":
        name = request.form.get("name")
        age = request.form.get("age")

        DATA_DICT[nid]["name"] = name
        DATA_DICT[nid]["age"] = age

        # urlfor() 表示跳转到路由的别名，idx是index的别名
        return redirect(url_for("idx"))

    return render_template("edit.html", info=info)


# 通过route接收get传过来的data，<int:nid>表示将nid转为int类型
@app.route("/delete/<int:nid>")
@auth
def delete(nid):
    del DATA_DICT[nid]
    return redirect(url_for("idx"))


@app.route("/")
def home():
    return redirect("/login")


if __name__ == "__main__":
    app.run(debug=True)


"""
1. 路由参数【路由，传值方法，别名】
@app.route("/index", methods=["GET", "POST"], endpoint="idx")
def index():
    pass

2. 动态路由【路由中传值】
@app.route("/index")
def index():
    pass
    
@app.route("/index/<name>")
def index(name):
    pass

@app.route("/index/<int:nid>")
def index(nid):
    pass
    
3. 获取提交的数据
@app.route("/index")
def index():
    request.args  # 获取GET形式的参数
    request.form  # 获取POST形式的参数

4. 返回数据
@app.route("/index")
def index():
    return render_template("模板文件")
    return jsonify()
    retutn redirect("index")  #  return redirect(url_for("idx"))
    return "..."  # 字符串

5. 模板处理

# 传递data
{{ data }}

# for循环传递data
{% for i in list %}
{{ i }}
{% endfor %}


"""
